'use client';

import React, { useState, useEffect } from 'react';
import { useCollaboration } from '@/hooks/use-collaboration';
import { Button } from '@/components/ui/button';
import { 
  Card, 
  CardContent, 
  CardDescription, 
  CardFooter, 
  CardHeader, 
  CardTitle 
} from '@/components/ui/card';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from '@/components/ui/dialog';
import { AlertCircle, Check, X, ArrowLeftRight, AlertTriangle } from 'lucide-react';
import { DiffViewer } from '@/components/editor/diff-viewer';
import { toast } from '@/components/ui/use-toast';

interface ConflictResolverProps {
  documentId?: string;
  isOpen?: boolean;
  onClose?: () => void;
  localContent?: any;
  remoteContent?: any;
  remoteUser?: { id: string; name: string };
  timestamp?: number;
  onResolve?: (resolution: 'local' | 'remote' | 'merged', content?: any) => void;
  className?: string;
}

export function ConflictResolver({ 
  documentId, 
  isOpen,
  onClose,
  localContent,
  remoteContent,
  remoteUser,
  timestamp,
  onResolve,
  className = '' 
}: ConflictResolverProps) {
  const { conflicts, resolveConflict } = useCollaboration();
  const [resolving, setResolving] = useState<Record<string, boolean>>({});
  const [showDialog, setShowDialog] = useState(!!isOpen);
  const [activeConflicts, setActiveConflicts] = useState<any[]>([]);
  const [mergeStrategy, setMergeStrategy] = useState<'smart' | 'theirs' | 'yours' | 'custom'>('smart');
  
  // 如果从props提供了冲突数据，使用它们
  useEffect(() => {
    if (isOpen !== undefined) {
      setShowDialog(isOpen);
    }
    
    if (localContent && remoteContent && remoteUser) {
      setActiveConflicts([{
        nodeId: 'modal-conflict',
        localContent,
        remoteContent,
        remoteUser,
        timestamp: timestamp || Date.now()
      }]);
    }
  }, [isOpen, localContent, remoteContent, remoteUser, timestamp]);
  
  // 否则，使用从useCollaboration获取的冲突
  useEffect(() => {
    if (!localContent && !remoteContent && conflicts.length > 0) {
      setActiveConflicts(conflicts);
    }
  }, [conflicts, localContent, remoteContent]);
  
  // 如果没有冲突且不是模态对话框模式，显示空状态
  if (activeConflicts.length === 0 && !isOpen) {
    return (
      <div className="flex flex-col items-center justify-center h-full p-4">
        <div className="text-muted-foreground text-center">
          <Check className="h-12 w-12 mx-auto text-green-500 mb-2" />
          <h3 className="text-lg font-medium">没有冲突</h3>
          <p>当前文档没有编辑冲突</p>
        </div>
      </div>
    );
  }
  
  // 处理冲突解决
  const handleResolveConflict = async (conflictId: string, useLocal: boolean) => {
    setResolving(prev => ({ ...prev, [conflictId]: true }));
    
    try {
      const conflict = activeConflicts.find(c => c.nodeId === conflictId);
      if (!conflict) return;
      
      // 根据选择使用本地或远程内容
      const resolution = useLocal ? conflict.localContent : conflict.remoteContent;
      
      if (onResolve) {
        // 如果提供了onResolve回调（模态对话框模式）
        onResolve(useLocal ? 'local' : 'remote', resolution);
        if (onClose) onClose();
      } else {
        // 否则使用resolveConflict函数
        await resolveConflict(conflictId, resolution);
        
        // 从活动冲突列表中移除
        setActiveConflicts(prev => prev.filter(c => c.nodeId !== conflictId));
        
        toast({
          title: '冲突已解决',
          description: `已选择${useLocal ? '您的' : '对方的'}版本`
        });
      }
    } catch (error) {
      console.error('解决冲突失败:', error);
      toast({
        title: '操作失败',
        description: '无法解决冲突',
        variant: 'destructive'
      });
    } finally {
      setResolving(prev => ({ ...prev, [conflictId]: false }));
    }
  };
  
  // 处理合并冲突
  const handleMergeConflict = async (conflictId: string, mergedContent?: any) => {
    setResolving(prev => ({ ...prev, [conflictId]: true }));
    
    try {
      const conflict = activeConflicts.find(c => c.nodeId === conflictId);
      if (!conflict) return;
      
      // 使用提供的合并内容或者使用默认策略
      let resolvedContent = mergedContent;
      
      if (!resolvedContent) {
        // 如果没有提供合并内容，根据合并策略生成
        switch (mergeStrategy) {
          case 'smart':
            // 智能合并逻辑（这需要一个更复杂的算法）
            // 这里简单实现，合并两者的非冲突部分
            resolvedContent = {
              ...conflict.localContent,
              ...conflict.remoteContent,
              _merged: true,
              _mergedAt: new Date().toISOString()
            };
            break;
          case 'theirs':
            resolvedContent = conflict.remoteContent;
            break;
          case 'yours':
            resolvedContent = conflict.localContent;
            break;
          case 'custom':
            // 自定义合并，应该由用户在UI中手动选择
            resolvedContent = mergedContent || conflict.localContent;
            break;
        }
      }
      
      if (onResolve) {
        // 如果提供了onResolve回调（模态对话框模式）
        onResolve('merged', resolvedContent);
        if (onClose) onClose();
      } else {
        // 否则使用resolveConflict函数
        await resolveConflict(conflictId, resolvedContent);
        
        // 从活动冲突列表中移除
        setActiveConflicts(prev => prev.filter(c => c.nodeId !== conflictId));
        
        toast({
          title: '冲突已解决',
          description: '已成功合并内容'
        });
      }
    } catch (error) {
      console.error('合并冲突失败:', error);
      toast({
        title: '合并失败',
        description: '无法合并内容',
        variant: 'destructive'
      });
    } finally {
      setResolving(prev => ({ ...prev, [conflictId]: false }));
    }
  };
  
  // 获取用户初始字母（用于头像）
  const getUserInitials = (name: string) => {
    return name
      .split(' ')
      .map(part => part[0])
      .join('')
      .toUpperCase()
      .substring(0, 2);
  };
  
  // 渲染冲突卡片
  const renderConflictCard = (conflict: any) => (
    <Card key={conflict.nodeId} className="overflow-hidden mb-4">
      <CardHeader className="bg-muted/30 pb-2">
        <div className="flex items-center justify-between">
          <div className="flex items-center gap-2">
            <AlertCircle className="h-5 w-5 text-destructive" />
            <CardTitle className="text-base">内容冲突</CardTitle>
          </div>
          <div className="flex items-center gap-2">
            <Avatar className="h-6 w-6">
              {conflict.remoteUser.image ? (
                <AvatarImage src={conflict.remoteUser.image} alt={conflict.remoteUser.name} />
              ) : (
                <AvatarFallback>{getUserInitials(conflict.remoteUser.name)}</AvatarFallback>
              )}
            </Avatar>
            <CardDescription>与 {conflict.remoteUser.name} 的编辑冲突</CardDescription>
          </div>
        </div>
      </CardHeader>
      
      <CardContent className="pt-4">
        <DiffViewer
          sourceContent={conflict.localContent}
          targetContent={conflict.remoteContent}
          sourceTitle="您的版本"
          targetTitle={`${conflict.remoteUser.name} 的版本`}
          onMerge={(mergedContent) => handleMergeConflict(conflict.nodeId, mergedContent)}
          onSelectSource={() => handleResolveConflict(conflict.nodeId, true)}
          onSelectTarget={() => handleResolveConflict(conflict.nodeId, false)}
        />
      </CardContent>
      
      <CardFooter className="flex justify-between gap-2 pt-2 pb-2 bg-muted/30">
        <div className="text-sm text-muted-foreground flex items-center">
          <AlertTriangle className="h-4 w-4 text-amber-500 mr-1" />
          请选择如何解决此冲突
        </div>
      </CardFooter>
    </Card>
  );
  
  // 如果是模态对话框模式
  if (isOpen !== undefined) {
    return (
      <Dialog open={showDialog} onOpenChange={(open) => {
        setShowDialog(open);
        if (!open && onClose) onClose();
      }}>
        <DialogContent className="max-w-3xl">
          <DialogHeader>
            <DialogTitle className="flex items-center gap-2">
              <AlertCircle className="h-5 w-5 text-destructive" />
              文档冲突检测
            </DialogTitle>
            <DialogDescription>
              检测到文档内容冲突，请选择如何解决
            </DialogDescription>
          </DialogHeader>
          
          {activeConflicts.map(renderConflictCard)}
        </DialogContent>
      </Dialog>
    );
  }
  
  // 渲染常规组件模式
  return (
    <div className={`space-y-4 ${className}`}>
      <div className="flex items-center justify-between">
        <h3 className="text-lg font-medium flex items-center gap-2">
          <AlertCircle className="h-5 w-5 text-destructive" />
          <span>编辑冲突</span>
        </h3>
        <span className="text-sm text-muted-foreground">
          {activeConflicts.length} 个冲突需要解决
        </span>
      </div>
      
      {activeConflicts.map(renderConflictCard)}
    </div>
  );
} 